/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
//事件配置管理-甘特图页面
import React, { Component } from 'react';
import styles from './index.less';
import { Divider, Collapse, Icon, Select, Input, notification, Form, TreeSelect, message, Spin, Breadcrumb, Button } from 'antd';
import PublicService from "../../../services/PublicService";
import request from '../../../utils/request';
import JSGanttComponent from 'react-jsgantt';
import Edit_Wrap from './Edit_Wrap';
import EventEdit from './EventEdit';
import Edit_Small from './Edit_Small';
import moment from 'moment';
import Edit_Appeal from './Edit_Appeal';
const { Panel } = Collapse;
const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
const { SHOW_CHILD } = TreeSelect;
const ButtonGroup = Button.Group;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315525_rx31ee175db.js',
});
class GtteWrap extends Component {


  constructor(props) {
    super(props);

    const vAdditionalHeaders = {
      required: { title: '事件必选' },
      pzState: { title: '配置状态' },
      planStartTime: { title: '计划开始时间', width: 200 },
      planEndTime: { title: '计划结束时间' },
      workTime: { title: '工期' },
      proposeTask: { title: '前置任务' },
      number: { title: '序号' }
    };

    this.state = {
      projectStatusThree: '1',//WBS按钮状态
      EditDataSmall: {},
      MyModal1VisibleSmall: false,
      MyModal1Visible: false,
      modalBtnLoading: false,
      title: '项目xx编辑',
      addWrap: false,
      Edit_Wrap: false,
      data: [],
      editWrap: false,
      EditArr: [],
      EditData: {},
      count: 0,
      Edit_Appeal: false,
      spinning: true
    }






    this.editorOptions = {
      vCaptionType: 'Complete',  // Set to Show Caption : None,Caption,Resource,Duration,Complete,控制右边图形结尾显示
      vQuarterColWidth: 36,
      vDateTaskDisplayFormat: ' yyyy-mm-dd', // Shown in tool tip box
      vDayMajorDateDisplayFormat: ' yyyy-mm-dd', // Set format to display dates in the "Major" header of the "Day" view
      vWeekMinorDateDisplayFormat: 'dd 日', // Set format to display dates in the "Minor" header of the "Week" view
      vLang: 0,
      vUseSingleCell: 0,
      vShowRes: 0,
      vShowCost: 0,
      vShowComp: 0,
      vShowDur: 0,
      vShowStartDate: 0,
      vShowEndDate: 0,
      vShowPlanStartDate: 0,
      vShowPlanEndDate: 0,
      vShowTaskInfoEndDate: 0,
      vShowTaskInfoLink: parseInt(this.vShowTaskInfoLink, 10), // Show link in tool tip (0/1)
      // Show/Hide the date for the last day of the week in header for daily view (1/0)
      // vTaskInfo: 0,
      vAdditionalHeaders: vAdditionalHeaders,//左边表格头部
      vEvents: {
        taskname: this.onEvent.bind(this, this.state.data),//点击触发
        res: 0,
        dur: 0,
        comp: 0,
        start: 0,
        end: 0,
        planstart: 0,
        planend: 0,
        cost: 0
      },
      vEventsChange: {
        taskname: this.editValue.bind(this, this.state.data),//编辑触发
        res: this.editValue.bind(this, this.state.data),
        dur: this.editValue.bind(this, this.state.data),
        comp: this.editValue.bind(this, this.state.data),
        start: this.editValue.bind(this, this.state.data),
        end: this.editValue.bind(this, this.state.data),
        planstart: this.editValue.bind(this, this.state.data),
        planend: this.editValue.bind(this, this.state.data),
        cost: this.editValue.bind(this, this.state.data)
      },
      vResources: [
        { id: 0, name: 'Anybody' },
        { id: 1, name: 'Mario' },
        { id: 2, name: 'Henrique' },
        { id: 3, name: 'Pedro' }
      ],
      // vEventClickRow: console.log,
      vTooltipDelay: 1,
      vDebug: false,
      vEditable: false,//是否可以编辑
      vUseSort: 'true',
      vFormatArr: ['Day', 'Week', 'Month'],//切换控制日期选择,日,周,月
    };
  }

  componentDidMount() {
    request({
      url: `/pm-web/projectmanage/eventinfo/getGanttData?projectId=${this.props.id}`,
      method: 'GET',
    }).then(data => {
      this.setState({
        data: data.ret.ganttList,
        count: data.ret.count,
        spinning: false
      })
    })
    //查询WBS按钮状态
    this.getProjectInfo()
  }

  getProjectInfo = () => {
    request({
      url: '/pm-web/projectmanage/projectinfo/getProjectInfo',
      method: 'POST',
      data: { projectId: this.props.id }
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          projectStatusThree: data.ret.projectStatusThree
        })

      }
    })
  }

  editValue(list, task, event, cell, column) {
    // tslint:disable-next-line:triple-equals
    const found = list.find(item => item.pID == task.getOriginalID());
    if (!found) {
      return;
    } else {
      found[column] = event ? event.target.value : '';
    }
    // console.log(found);
  }

  change() {
    // console.log('change:', this.editor);
    // console.log('change2:', this.editorTwo);
  }

  setLanguage(lang) {
    this.editorOptions.vLang = lang;
    this.editor.setOptions(this.editorOptions);
  }

  customLanguage() {
    // this.editorOptions.languages = {
    //   'pt-BR': {
    //     'auto': 'Automático testing'
    //   },
    //   'en': {
    //     'auto': 'Auto testing'
    //   }
    // };
    this.editor.setOptions(this.editorOptions);
  }

  changeObject() {
    this.state.data.randomNumber = Math.random() * 100;
  }

  changeData() {
    this.state.data = Object.assign({}, this.state.data,
      { randomNumber: Math.random() * 100 });
  }



  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
  };






  //保存按钮事件
  onModalSave = (v) => {
    this.setState({
      spinning: true
    })
    // console.log(v, 44)
    let params = {
      eventId: this.state.eventId,
      milepost: v.milepost,
      userIds: v.safetyInformationList
    }
    request({
      url: '/pm-web/projectmanage/eventinfo/updateEventInfo1',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success("修改成功")
        request({
          url: `/pm-web/projectmanage/eventinfo/getGanttData?projectId=${this.props.id}`,
          method: 'GET',
        }).then(data => {
          // console.log(data)
          this.setState({
            data: data.ret.ganttList,
            count: data.ret.count,
            spinning: false
          })
        })
      } else {
        message.warning("修改失败")
      }


    })


  }


  selectedChange(fun, nextParams, paramName, index, value) {
    // console.log(fun, nextParams, paramName, index, value)


    let t = this;
    let params = {};
    params[paramName] = value;
    if (paramName) {
      t.setState({ params }, () => {
      });
    }
    if (typeof fun === "function") {
      fun(value);
      if (nextParams)
        t.props.form.setFieldsValue({
          [nextParams]: ''
        })
    }
  }

  onEdit = () => {
    this.setState({
      Edit_Wrap: true
    })
  }

  onEvent = (list, task, event, cell, column) => {
    // console.log(list, task.getLink(), event, cell, column)
    // task.getOriginalID()  获取点击项目的id
    // console.log(task.getGroup(),  task.getParent(), task.getOriginalID(),task.getParItem().getOriginalID(),task)

    if (task.getParent() == 0) {
      return
    }

    if (Number(task.getParItem().getOriginalID() < 5)) {
      //大事件
      request({
        url: '/pm-web/projectmanage/eventinfo/getEventInfoByEventId',
        method: 'POST',
        data: { eventId: task.getOriginalID() }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditData: data.ret,
            MyModal1Visible: true,
            eventId: task.getOriginalID()
          })


        }
      })
    } else {
      //小事件
      request({
        url: '/pm-web/projectmanage/subeventsInfo/getSubeventsInfoBysubeventsId',
        method: 'POST',
        data: { subeventsId: task.getOriginalID(), projectId: this.props.id }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditDataSmall: data.ret,
            MyModal1VisibleSmall: true,
            subeventsId: task.getOriginalID(),
            eventId: task.getOriginalID()
          })


        }
      })
    }




  }
  //子事件保存
  onModalSaveSmall = (v) => {
    this.setState({
      spinning: true,
      modalBtnLoading: true
    })

    // if(moment(v.planStartTime).isBefore(moment(v.planEndTime))){

    // }else{
    //   message.warning("请输入正确的计划时间!")
    //   return
    // }

    console.log(v, 44)
    let params = {
      confirmUserId: v.confirmUserId,
      planEndTime: moment(v.planEndTime).format("YYYY-MM-DD"),
      planStartTime: moment(v.planStartTime).format("YYYY-MM-DD"),
      subeventsId: this.state.subeventsId,
      subeventsWeight: v.subeventsWeight,
      workTime: v.workTime,
      auditCcUsers: v.auditCcUsers,
      auditUsers: v.auditUsers,
      oaUserArr: v.oaUserArr,
      userIds: v.safetyInformationUser,
      milepost: v.milepost
    }
    request({
      url: '/pm-web/projectmanage/subeventsInfo/updateEventInfo1',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success("修改成功")
        request({
          url: `/pm-web/projectmanage/eventinfo/getGanttData?projectId=${this.props.id}`,
          method: 'GET',
        }).then(data => {
          // console.log(data)
          this.setState({
            data: data.ret.ganttList,
            count: data.ret.count,

          })
        })
      } else {
        message.warning(`${data.err}`)
      }


      this.setState({
        MyModal1VisibleSmall: false,
        spinning: false,
        modalBtnLoading: false
      })


    })

  }

  goBack = () => {
    this.props.goBack()
  }
  //二级页面关闭
  goBackTwo = () => {
    this.setState({
      Edit_Wrap: false,
      spinning: true
    })
    //刷新甘特图
    request({
      url: `/pm-web/projectmanage/eventinfo/getGanttData?projectId=${this.props.id}`,
      method: 'GET',
    }).then(data => {
      // console.log(data)
      this.setState({
        data: data.ret.ganttList,
        count: data.ret.count,
        spinning: false
      })
    })
  }


  onWbs = () => {

  }


  //提交审批
  onSave = () => {
    this.setState({
      spinning: true
    })

    request({
      url: '/pm-web/projectmanage/eventinfo/submitExamine',
      method: 'POST',
      data: { projectId: this.props.id, userId: PublicService.getCookie('userId') }
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {
        message.success("提交审批成功!")
        this.goBack()
      } else {
        message.warning(`${data.err}`)
      }
      this.setState({
        spinning: false
      })
    })
  }

  openNotification = () => {

    if (this.state.projectStatusThree == 2) {
      message.warning('WBS已提醒过了!')
      return
    }
    this.setState({
      spinning: true
    })
    request({
      url: '/pm-web/projectmanage/progress/remindPersonnelSetupWBS',
      method: 'POST',
      data: { projectId: this.props.id }
    }).then(data => {
      if (data.rc === 0) {
        //查询WBS按钮状态
        this.getProjectInfo()
        notification.open({
          message: 'WBS分解提示',
          description:
            '已通知审算部人员进行WBS分解.',
          onClick: () => {
            // console.log('Notification Clicked!');
          },
        });
      } else {
        notification.open({
          message: 'WBS分解提示',
          description:
            '提醒失败,请重新操作!',
          onClick: () => {
            // console.log('Notification Clicked!');
          },
        });
      }

      this.setState({
        spinning: false
      })

    })




  }

  //导出
  exportBtn = (val) => {
    let t = this;
    window.location.href = `/pm-web/projectmanage/eventinfo/exportAllocation?projectId=${this.props.id}`
  };
  //事件配置-编辑
  getEdit_Wrap = () => {
    return (
      <Edit_Wrap id={this.props.id} goBackTwo={this.goBackTwo} />
    )
  }

  //事件配置-提交审批
  getEdit_Appeal = () => {
    return (
      <Edit_Appeal id={this.props.id} goBackTwo={this.goBackTwo} />
    )
  }

  //事件配置-甘特图主页面
  getWarp = () => {
    let t = this
    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '76vh';
    let tableHeight = 310;
    if (width > 1367) {
      tableHeight = 380;
      containerHeight = '83vh';
    }

    const { modalBtnLoading, Edit_Wrap, Edit_Appeal, spinning } = this.state;

    return (
      <div className={styles.warpBox}>
        <Spin spinning={spinning} size='large'>
          <div className={styles.Top_Box} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 0, border: '2px solid #fff', borderRadius: '6px 6px 0px 0px', height: 30, alignItems: 'center' }}>
            <span style={{ fontWeight: 700, marginLeft: 10, width: '50%' }}>
              <Breadcrumb>
                <Breadcrumb.Item>事件配置管理</Breadcrumb.Item>
                <Breadcrumb.Item>
                  编辑-{this.props.title}
                </Breadcrumb.Item>
              </Breadcrumb></span> <IconFont type="icon-guanbi" onClick={this.goBack} style={{ marginRight: 10, cursor: 'pointer' }} />

          </div>


          <div className={styles.Top_Box} style={{ backgroundColor: '#fff', height: 30, alignItems: 'center', paddingLeft: 15, display: this.props.warpFlag ? '' : 'none' }}>
            <ButtonGroup size={'small'}>
              <Button onClick={this.onEdit}>编辑</Button>
              <Button onClick={this.openNotification}>{this.state.projectStatusThree == 1 ? 'WBS提醒' : 'WBS已提醒'}</Button>
              <Button onClick={this.onSave}>提交审批</Button>
              <Button onClick={this.exportBtn}>项目导出</Button>
            </ButtonGroup>
            <Divider type="vertical" />
            <span >未完成配置数量 : ( {this.state.count} )</span>
          </div>

          <div style={{ backgroundColor: '#fff', overflow: 'auto', height: '80vh' }} className={styles.gantt}>
            {/* 大事件编辑页面 */}
            {
              this.state.MyModal1Visible && <EventEdit
                ModalCancel={this.ModalCancel.bind(this, 'MyModal1Visible')}
                EditData={this.state.EditData}
                onModalSave={this.onModalSave}
              />
            }
            {/* 小事件编辑页面 */}
            {
              this.state.MyModal1VisibleSmall && <Edit_Small
                ModalCancel={this.ModalCancel.bind(this, 'MyModal1VisibleSmall')}
                EditData={this.state.EditDataSmall}
                onModalSave={this.onModalSaveSmall}
                warpFlag={this.props.warpFlag}
                modalBtnLoading={modalBtnLoading}
              />
            }
            <div style={{ flex: 1, overflow: 'auto' }}>
              <JSGanttComponent data={this.state.data} options={this.editorOptions} />
            </div>
          </div>
        </Spin>
      </div>
    )
  }

  render() {
    let t = this
    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '76vh';
    let tableHeight = 310;
    if (width > 1367) {
      tableHeight = 380;
      containerHeight = '83vh';
    }

    const { Edit_Wrap, Edit_Appeal } = this.state;




    return (
      <div>
        {this.state.Edit_Wrap && this.getEdit_Wrap()}
        {/* {this.state.Edit_Appeal && this.getEdit_Appeal()} */}
        {!this.state.Edit_Wrap ? this.getWarp() : ''}
        {/* {!this.state.Edit_Wrap && !this.state.Edit_Appeal ?this.getWarp():''} */}


      </div>
    );


  }

}
export default GtteWrap;

